﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using StackExchange.Redis;
using XYS.Core.Models;
using XYS.Core.Util;
using XYS.Core.Util.Helper;
using XYS.Service.Core.Consumers.Base;
using XYS.Service.Core.HostedServices;
using XYS.Service.Core.Models;
using XYS.Service.Core.Service;
using XYS.Service.Core.Util.Helper;

namespace XYS.Service.Core
{
    /// <summary>
    /// 缓存服务 相关配置
    /// </summary>
    public static class RabbitMQExtension
    {
        /// <summary>
        /// 增加分布式缓存
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static WebApplicationBuilder AddMQ(this WebApplicationBuilder builder, ILogger logger)
        {
            var rabbitMQSetting = builder.Configuration.GetSection("MQSetting").Get<RabbitMQSetting>();
            if (rabbitMQSetting != null)
            {
                logger.Log(LogLevel.Information, $"注册MQ消息队列\r\n{rabbitMQSetting.Hosts.ToJson()}");
                MQHelper.Init(rabbitMQSetting);

                //注册所有的 消费者
                var consumers = AssemblyHelper.GetAssemblyTypes().Where(e => typeof(IConsumerBase).IsAssignableFrom(e)
                    && e.IsClass
                    && !typeof(ConsumerBase<object, object>).FullName.Contains(e.FullName))
                .Where(x => x != null && !string.IsNullOrWhiteSpace(x.FullName)).ToList();

                if (!consumers.IsNullOrEmpty())
                {

                    builder.Services.AddHostedService<MQConsumersHostedService>();
                    foreach (var item in consumers)
                    {
                        logger.LogInformation($"注册MQ消费者：【{item.Name}】");
                        builder.Services.AddSingleton(item);
                    }
                }
            }

            var rabbitMQLocalSetting = builder.Configuration.GetSection("MQLocalSetting").Get<RabbitMQSetting>();
            if (rabbitMQLocalSetting != null && rabbitMQLocalSetting.Enable)
            {
                logger.Log(LogLevel.Information, $"注册本地MQ消息队列\r\n{rabbitMQLocalSetting.Hosts.ToJson()}");
                MQLocalHelper.Init(rabbitMQLocalSetting);
            }
            return builder;
        }

    }
}
